"use strict"

const mvc = require("cosjs.mvc");

exports.index = function(){
    let id = this.get("id",'string');
    if(!id){
        return this.error("id empty")
    }
    this.view = "jqgrid";
    let data = {"view":"forms/values","handle":"branch/forms/values"};
    return Promise.resolve().then(()=>{
        let formsNavbar = this.model.branch("forms/navbar",this.branch);
        return formsNavbar.get(id).then(ret=>{
            if(!ret){
                return this.error("formsNavbar not exist",id)
            }
            data['title'] = ret['name'];
            data['navbar'] = ret;
        })
    }).then(()=>{
        let formsFields = this.model.branch("forms/fields",this.branch);
        let query = {"fid":id};
        let option = {"multi":true,"dataType":"array","sort":{"sort":1} };
        return formsFields.find(query,option).then(ret=>{
            data['fieids'] = [];
            if(!ret){
                return
            }
            for(let v of ret){
                let attr = v.attr;
                delete v._id;delete v.fid;delete v.attr;delete v.sort;
                if(!v.formatter){
                    delete v.formatter;
                }
                if(attr && typeof attr === 'object'){
                    Object.assign(v,attr);
                }
                data['fieids'].push(v);
            }
        })
    }).then(()=>{
        data['sid'] = this.get("sid",'int')||1;
        data["server"] = {};
        let keys = ["name"]
        let server = this.model.branch("server",this.branch);
        return server.mget(keys).then(ret=>{
            for(let k in ret){
                let v = ret[k];
                let sid = v._id;
                data["server"][sid] = v.name;
            }
        })
    }).then(()=>{
        data['jqgrid'] = {"add":data['navbar']['add']?true:false,"edit":data['navbar']['edit']?true:false,"del":data['navbar']['del']?true:false };
        return data;
    })

}
//游戏服务器列表管理
exports.page = function (){
    this.output = 'json';
    let id = this.get("id",'string');
    let sid = this.get('sid','int');

    if(!id){
        return this.error("id empty")
    }
    if(!sid){
        return this.error("sid empty")
    }

    let formsNavbar = this.model.branch("forms/navbar",this.branch);
    return formsNavbar.get(id).then(ret=>{
        if(!ret){
            return this.error("formsNavbar not exist",id)
        }
        if(!ret['api']){
            return this.error("formsNavbar pageurl empty",id)
        }
        
        if(ret['ut']==0){
            let api = ['',ret['api'],'page'].join('/');
            if(ret['query']){
                api = [api,ret['query']].join("?");
            }
            return this.library("game/request",this.branch,sid,api,this.req.body||{});
        }
        else if(ret['ut']==1){
            return handle_page.call(this,ret['api'],sid);
            //let model = this.model.branch(ret['api'],this.branch,sid);
            //return this.library("game/request",this.branch,sid,api,this.req.body||{});
        }
        else {
            return this.error('forms ut error')
        }
    })

};

//游戏服务器列表管理
exports.save = function (){
    this.output = 'json';
    let id = this.get("id",'string');
    let sid = this.get('sid','int');

    if(!id){
        return this.error("id empty")
    }
    if(!sid){
        return this.error("sid empty")
    }

    let formsNavbar = this.model.branch("forms/navbar",this.branch);
    return formsNavbar.get(id).then(ret=>{
        if(!ret){
            return this.error("formsNavbar not exist",id)
        }
        if(!ret['api']){
            return this.error("formsNavbar pageurl empty",id)
        }
        
        if(ret['ut']==0){
            let api = ['',ret['api'],'save'].join('/');
            return this.library("game/request",this.branch,sid,api,this.req.body||{});
        }
        else if(ret['ut']==1){
            return handle_save.call(this,ret['api'],sid);
        }
        else {
            return this.error('forms ut error')
        }
    })

};



function handle_page(api,sid){
    let $page = this.get('page', 'int') || 1;
    let $size = this.get('size', 'int') || 20;
    let $sort = this.get('sort','string') ;
    let $order = this.get('order') || 'desc';
    let dbsort = {};
    if ($sort) {
        dbsort[$sort] = $order == 'desc' ? -1 : 1;
    }

    let fk = ['branch',api].join('/');
    let query = {} ,body = this.req.body;
    let format = mvc.format(fk);
    if(format){
        query = this.library.call(this,'jqgrid/query',body,format);
    }
    let option = {"total":this.get('total', 'int') || 0};
    let model = this.model.branch(api,this.branch,sid);
    return model.page(query, $page, $size, dbsort, option);
};


function handle_save(api,sid){
    return this.error('还没做好')
};